package com.example.port.service.impl;

import com.example.port.dto.AuthRequest;
import com.example.port.dto.AuthResponse;
import com.example.port.dto.RegisterRequest;
import com.example.port.entity.User;
import com.example.port.exception.ServiceException;
import com.example.port.service.AuthService;
import com.example.port.service.UserService;
import com.example.port.utils.JwtUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {
    
    private final UserService userService;
    private final JwtUtils jwtUtils;
    private final AuthenticationManager authenticationManager;
    
    @Override
    public AuthResponse register(RegisterRequest request) {
        // 检查用户名是否已存在
        if (userService.existsByUsername(request.getUsername())) {
            throw new ServiceException("用户名已存在");
        }
        
        // 创建用户实体
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(request.getPassword());
        user.setEmail(request.getEmail());
        // 设置默认角色
        user.setRole("USER");
        // 显式设置用户为激活状态
        user.setActive(true);
        user.setIsActive(true);
        
        // 保存用户
        User savedUser = userService.createUser(user);
        
        // 生成token
        String token = jwtUtils.generateToken(savedUser);
        
        // 返回认证响应
        return AuthResponse.builder()
                .token(token)
                .user(savedUser)
                .build();
    }
    
    @Override
    public AuthResponse authenticate(AuthRequest request) {
        try {
            // 进行认证
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            request.getUsername(),
                            request.getPassword()
                    )
            );
            
            // 获取认证用户名
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            String username = userDetails.getUsername();
            
            // 获取对应的User实体
            User user = userService.getUserByUsername(username);
            if (user == null) {
                throw new ServiceException("用户不存在");
            }
            
            // 生成token
            String token = jwtUtils.generateToken(user);
            
            // 返回认证响应
            return AuthResponse.builder()
                    .token(token)
                    .user(user)
                    .build();
        } catch (AuthenticationException e) {
            throw new ServiceException("认证失败：" + e.getMessage());
        }
    }
}  
